<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title></title>
</head>
<body>
	<input type="text" name="">
	<button>查询</button>
	<img src="">
	<script type="text/javascript">
		let btn = document.querySelector("button")
		let inp = document.querySelector("input")
		let img = document.querySelector("img")
		const KEY = 'c494e264764449f7b4f6bf742276d7f9'
		// 用promis封装一下天气接口

		// 封装城市查询接口 Promise
		function getCityId(location) {
  			return new Promise((resolve, reject) => {
    			let xhr = new XMLHttpRequest()
   				 xhr.open("get", `https://geoapi.qweather.com/v2/city/lookup?location=${location}&key=${KEY}`)
   				xhr.send()
    			xhr.onreadystatechange = function() {
      				if (xhr.readyState === 4) {
        				if (xhr.status === 200) {
          					let res = JSON.parse(xhr.responseText)
          					res.code === "200" ? resolve(res) : reject(res)
        				} else {
         					reject(new Error('城市查询请求失败'))
        				}
      				}
    			}
 			 })
			}


		// 封装天气查询接口 Promise (修改了正确的API地址)
		function getWeather(cityId) {
  			return new Promise((resolve, reject) => {
    			let xhr = new XMLHttpRequest()
    			xhr.open("get", `https://api.qweather.com/v7/weather/now?location=${cityId}&key=${KEY}`)
    			xhr.send()
    			xhr.onreadystatechange = function() {
      				if (xhr.readyState === 4) {
        				if (xhr.status === 200) {
          				let res = JSON.parse(xhr.responseText)
         			 	res.code === "200" ? resolve(res) : reject(res)
        			} else {
          				reject(new Error('天气查询请求失败'))
        			}
      			}
    		}
  		})
		}

		// 异步处理点击事件
		btn.onclick = async function() {
		  	try {
		    // 顺序执行两个 Promise
		    const cityData = await getCityId(inp.value)
		    const weatherData = await getWeather(cityData.location[0].id)
		    
		    // 动态设置天气图标
		    const icon = weatherData.now.icon
		    img.src = `https://a.hecdn.net/img/common/icon/202106d/${icon}.png`
		    img.alt = weatherData.now.text
		    
		  } catch (error) {
		    console.error('请求失败:', error)
		    alert(`获取天气失败: ${error.message || error.code}`)
		  }
		}
	</script>
</body>
</html>